package com.arelikebrothers.demo.java8.stream;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * Created by qiuzhongrun on 01/05/2017.
 */
public class CpuProvider {

    public synchronized String getCpuUsage() {
        String result = "0%";

        Process process = null;
        try {
            Thread.sleep(1000);
//            process = new ProcessBuilder("ps -A -o %cpu | awk '{s+=$1} END {print s \"%\"}'").start();
            List<String> cmds = new ArrayList<>();
            cmds.add("sh");
            cmds.add("-c");
            cmds.add("top |head -4 |tail -1");
            ProcessBuilder processBuilder = new ProcessBuilder(cmds);
            process = processBuilder.start();

            OutputStream outputStream = process.getOutputStream();


            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
            }

            result = builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }


    public static void main(String[] args) {
            Stream.generate(new CpuProvider()::getCpuUsage).forEach(System.out::print);
    }
}
